package com.example.dictionary.service;

import com.example.dictionary.config.DictionaryProperties;
import com.example.memento.model.WordEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 词典文件解析服务
 */
@Service
public class DictionaryParseService {
    
    private static final Logger log = LoggerFactory.getLogger(DictionaryParseService.class);
    
    private final DictionaryProperties properties;
    private final ExecutorService executorService;
    
    public DictionaryParseService(DictionaryProperties properties) {
        this.properties = properties;
        this.executorService = Executors.newFixedThreadPool(properties.getParsing().getThreadPoolSize());
    }
    
    /**
     * 解析词典文件
     */
    public CompletableFuture<List<WordEntry>> parseFile(Path filePath, String sourceName, String format) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                log.info("开始解析词典文件: {} (格式: {})", filePath, format);
                
                List<WordEntry> entries = switch (format.toLowerCase()) {
                    case "cedict" -> parseCedictFile(filePath, sourceName);
                    case "wordnet" -> parseWordnetFile(filePath, sourceName);
                    case "json" -> parseJsonFile(filePath, sourceName);
                    case "csv" -> parseCsvFile(filePath, sourceName);
                    default -> parseTextFile(filePath, sourceName);
                };
                
                log.info("词典文件解析完成: {} 条目数: {}", filePath, entries.size());
                return entries;
                
            } catch (Exception e) {
                log.error("解析词典文件失败: {}", filePath, e);
                throw new RuntimeException("文件解析失败", e);
            }
        }, executorService);
    }
    
    /**
     * 解析CEDICT格式文件
     * CEDICT格式: 中文词 拼音 [词性] /英文翻译1/英文翻译2/
     */
    private List<WordEntry> parseCedictFile(Path filePath, String sourceName) throws IOException {
        List<WordEntry> entries = new ArrayList<>();
        
        // CEDICT格式正则表达式
        Pattern cedictPattern = Pattern.compile("^([^\\s]+)\\s+([^\\s]+)\\s+\\[(.+?)\\]\\s+(.+)$");
        
        try (BufferedReader reader = Files.newBufferedReader(filePath)) {
            String line;
            int lineNumber = 0;
            
            while ((line = reader.readLine()) != null) {
                lineNumber++;
                
                // 跳过注释行
                if (line.startsWith("#") || line.trim().isEmpty()) {
                    continue;
                }
                
                try {
                    Matcher matcher = cedictPattern.matcher(line);
                    if (matcher.matches()) {
                        WordEntry entry = new WordEntry();
                        entry.setWord(matcher.group(1));
                        entry.setPronunciation(matcher.group(2));
                        entry.setPartOfSpeech(matcher.group(3));
                        
                        String translations = matcher.group(4);
                        // 移除开头的斜杠并分割翻译
                        if (translations.startsWith("/")) {
                            translations = translations.substring(1);
                        }
                        if (translations.endsWith("/")) {
                            translations = translations.substring(0, translations.length() - 1);
                        }
                        
                        entry.setTranslation(translations);
                        entry.setSource(sourceName);
                        entry.setLanguage("zh");
                        entry.setTargetLanguage("en");
                        
                        entries.add(entry);
                    }
                } catch (Exception e) {
                    log.warn("解析第{}行失败: {}", lineNumber, line);
                }
            }
        }
        
        return entries;
    }
    
    /**
     * 解析WordNet格式文件
     */
    private List<WordEntry> parseWordnetFile(Path filePath, String sourceName) throws IOException {
        List<WordEntry> entries = new ArrayList<>();
        
        try (BufferedReader reader = Files.newBufferedReader(filePath)) {
            String line;
            WordEntry currentEntry = null;
            
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                
                if (line.startsWith("<word>")) {
                    currentEntry = new WordEntry();
                    currentEntry.setWord(extractXmlContent(line));
                    currentEntry.setSource(sourceName);
                    currentEntry.setLanguage("en");
                    currentEntry.setTargetLanguage("en");
                } else if (line.startsWith("<definition>") && currentEntry != null) {
                    currentEntry.setDefinition(extractXmlContent(line));
                } else if (line.startsWith("<example>") && currentEntry != null) {
                    currentEntry.setExample(extractXmlContent(line));
                } else if (line.startsWith("</word>") && currentEntry != null) {
                    entries.add(currentEntry);
                    currentEntry = null;
                }
            }
        }
        
        return entries;
    }
    
    /**
     * 解析JSON格式文件
     */
    private List<WordEntry> parseJsonFile(Path filePath, String sourceName) throws IOException {
        // 这里简化处理，实际应该使用Jackson解析JSON
        List<WordEntry> entries = new ArrayList<>();
        
        try (BufferedReader reader = Files.newBufferedReader(filePath)) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("{") && line.endsWith("}")) {
                    // 简单的JSON解析，实际项目中应使用Jackson
                    WordEntry entry = parseSimpleJson(line, sourceName);
                    if (entry != null) {
                        entries.add(entry);
                    }
                }
            }
        }
        
        return entries;
    }
    
    /**
     * 解析CSV格式文件
     */
    private List<WordEntry> parseCsvFile(Path filePath, String sourceName) throws IOException {
        List<WordEntry> entries = new ArrayList<>();
        
        try (BufferedReader reader = Files.newBufferedReader(filePath)) {
            String line;
            boolean isFirstLine = true;
            
            while ((line = reader.readLine()) != null) {
                if (isFirstLine) {
                    isFirstLine = false;
                    continue; // 跳过标题行
                }
                
                String[] fields = line.split(",");
                if (fields.length >= 2) {
                    WordEntry entry = new WordEntry();
                    entry.setWord(fields[0].trim());
                    entry.setTranslation(fields[1].trim());
                    entry.setSource(sourceName);
                    
                    if (fields.length >= 3) {
                        entry.setDefinition(fields[2].trim());
                    }
                    if (fields.length >= 4) {
                        entry.setExample(fields[3].trim());
                    }
                    
                    entries.add(entry);
                }
            }
        }
        
        return entries;
    }
    
    /**
     * 解析普通文本文件
     */
    private List<WordEntry> parseTextFile(Path filePath, String sourceName) throws IOException {
        List<WordEntry> entries = new ArrayList<>();
        
        try (BufferedReader reader = Files.newBufferedReader(filePath)) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (!line.isEmpty() && !line.startsWith("#")) {
                    // 简单的制表符或空格分割
                    String[] parts = line.split("\\s+", 2);
                    if (parts.length >= 2) {
                        WordEntry entry = new WordEntry();
                        entry.setWord(parts[0]);
                        entry.setTranslation(parts[1]);
                        entry.setSource(sourceName);
                        entries.add(entry);
                    }
                }
            }
        }
        
        return entries;
    }
    
    /**
     * 从XML标签中提取内容
     */
    private String extractXmlContent(String xmlLine) {
        int start = xmlLine.indexOf('>') + 1;
        int end = xmlLine.lastIndexOf('<');
        if (start > 0 && end > start) {
            return xmlLine.substring(start, end).trim();
        }
        return "";
    }
    
    /**
     * 简单的JSON解析（仅用于演示）
     */
    private WordEntry parseSimpleJson(String jsonLine, String sourceName) {
        // 这是一个简化的JSON解析，实际项目中应使用Jackson
        try {
            WordEntry entry = new WordEntry();
            
            // 提取word字段
            Pattern wordPattern = Pattern.compile("\"word\"\\s*:\\s*\"([^\"]+)\"");
            Matcher wordMatcher = wordPattern.matcher(jsonLine);
            if (wordMatcher.find()) {
                entry.setWord(wordMatcher.group(1));
            }
            
            // 提取translation字段
            Pattern translationPattern = Pattern.compile("\"translation\"\\s*:\\s*\"([^\"]+)\"");
            Matcher translationMatcher = translationPattern.matcher(jsonLine);
            if (translationMatcher.find()) {
                entry.setTranslation(translationMatcher.group(1));
            }
            
            entry.setSource(sourceName);
            return entry;
        } catch (Exception e) {
            log.warn("解析JSON行失败: {}", jsonLine);
            return null;
        }
    }
}
